<template>
    <div v-if="isLoading" class="loading-container">
        <el-spin tip="加载中..." />
    </div>
    <div v-else style="display: flex; background-color: rgb(221.7, 222.6, 224.4); width: 100%; height: auto; padding: 20px;">
        <el-form ref="dataFormRef" :model="dataForm" label-width="120px" style="width: 100%;" :rules="rules">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="车次" prop="trainNumber">
                        <el-input v-model="dataForm.trainNumber" placeholder="请输入车次" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="列车ID" prop="trainId">
                        <el-input-number v-model="dataForm.trainId" placeholder="请输入列车ID" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="出发站城市">
                        <el-select v-model="dataForm.startStationCity" placeholder="请选择" style="width: 100%;">
                            <el-option v-for="item in stationCityList" :key="item" :label="item" :value="item" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="出发站名称">
                        <el-select v-model="dataForm.startStationName" placeholder="请选择" style="width: 100%;">
                            <el-option v-for="item in stationNameList" :key="item" :label="item" :value="item" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="中转站城市">
                        <el-select v-model="dataForm.transferStationCity" placeholder="请选择" style="width: 100%;" :disabled="isTransfer">
                            <el-option v-for="item in stationCityList" :key="item" :label="item" :value="item" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="中转站名称">
                        <el-select v-model="dataForm.transferStationName" placeholder="请选择" style="width: 100%;" :disabled="isTransfer">
                            <el-option v-for="item in stationNameList" :key="item" :label="item" :value="item" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="终点站城市">
                        <el-select v-model="dataForm.endStationCity" placeholder="请选择" style="width: 100%;">
                            <el-option v-for="item in stationCityList" :key="item" :label="item" :value="item" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="终点站名称">
                        <el-select v-model="dataForm.endStationName" placeholder="请选择" style="width: 100%;">
                            <el-option v-for="item in stationNameList" :key="item" :label="item" :value="item" />
                        </el-select>
                    </el-form-item>
                </el-col>


                <el-col :span="12">
                    <el-form-item label="始发站出发时间" prop="startStationStartTime">
                        <el-date-picker v-model="dataForm.startStationStartTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择发车时间" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="中转站到达时间">
                        <el-date-picker v-model="dataForm.transferStationEndTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择停车时间" style="width: 100%;" :disabled="isTransfer"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="中转站出发时间">
                        <el-date-picker v-model="dataForm.transferStationStartTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择发车时间" style="width: 100%;" :disabled="isTransfer"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="终点站到达时间" prop="endStationEndTime">
                        <el-date-picker v-model="dataForm.endStationEndTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择停车时间" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="商务座行数起始" prop="businessRowStart">
                        <el-input-number v-model="dataForm.businessRowStart" placeholder="请输入" :min="1" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="商务座行数结束" prop="businessRowEnd">
                        <el-input-number v-model="dataForm.businessRowEnd" placeholder="请输入" :min="1" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="普通座行数起始" prop="commonRowStart">
                        <el-input-number v-model="dataForm.commonRowStart" placeholder="请输入" :min="1" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="普通座行数结束" prop="commonRowEnd">
                        <el-input-number v-model="dataForm.commonRowEnd" placeholder="请输入" :min="1" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="商务座价格" prop="businessPrice">
                        <el-input-number v-model="dataForm.businessPrice" placeholder="请输入" :min="1" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="普通座价格" prop="commonPrice">
                        <el-input-number v-model="dataForm.commonPrice" placeholder="请输入" :min="1" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="是否中转">
                        <el-select v-model="dataForm.transferChoice" placeholder="请选择" style="width: 100%;">
                            <el-option v-for="item in transferChoiceOptions" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="路线状态">
                        <el-select v-model="dataForm.status" placeholder="请选择路线" style="width: 100%;">
                            <el-option v-for="item in routeStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item style="margin-top: 30px;margin-left: 350px; text-align: center;">
                <el-button type="primary" @click="onSubmit">提交</el-button>
                <el-button @click="router.push({ name: 'route' })">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router'
import { ref, reactive, onMounted, getCurrentInstance,computed } from 'vue'
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();
const dataFormRef = ref(null);
// 表单
const dataForm = reactive({
    routeId: null,
    trainNumber: null,
    trainId: null,
    startStationCity: null,
    startStationName: null,
    transferStationCity: null,
    transferStationName:null,
    endStationCity: null,
    endStationName: null,
    startStationStartTime: null,
    transferStationEndTime: null,
    transferStationStartTime: null,
    endStationEndTime: null,
    businessRowStart: null,
    businessRowEnd: null,
    commonRowStart: null,
    commonRowEnd: null,
    businessPrice: null,
    commonPrice: null,
    status: 1,
    transferChoice: 2, // 是否中转：1中转，2直达
});
// 表单提交校验
const rules ={
        trainNumber:[{required: true, message: '请输入车次', trigger: 'blur'}],
        trainId:[{required: true, message: '请输入火车id', trigger: 'blur'}],
        startStationCity:[{required: true, message: '请输入始发站城市', trigger: 'blur'}],
        startStationName:[{required: true, message: '请输入始发站名称', trigger: 'blur'}],
        endStationCity:[{required: true, message: '请输入终点站城市', trigger: 'blur'}],
        endStationName:[{required: true, message: '请输入终点站名称', trigger: 'blur'}],
        startStationStartTime:[{required: true, message: '请输入始发站出发时间', trigger: 'blur'}],
        endStationEndTime:[{required: true, message: '请输入终点站到达时间', trigger: 'blur'}],
        businessRowStart:[{required: true, message: '请输入商务座起始排数', trigger: 'blur'}],
        businessRowEnd:[{required: true, message: '请输入商务座结束排数', trigger: 'blur'}],
        commonRowStart:[{required: true, message: '请输入普通座起始排数', trigger: 'blur'}],
        commonRowEnd:[{required: true, message: '请输入普通座结束排数', trigger: 'blur'}],
        businessPrice:[{required: true, message: '请输入商务座价格', trigger: 'blur'}],
        commonPrice:[{required: true, message: '请输入普通座价格', trigger: 'blur'}],
        status:[{required: true, message: '请选择路线状态', trigger: 'blur'}],
    } 
// 路线状态
const routeStatusOptions = ref([
    {
        label: '禁用',
        value: 0
    },
    {
        label: '启用',
        value: 1
    },
    {
        label: '维修',
        value: 2
    }
])
// 是否中转
const transferChoiceOptions = ref([
{
        label: '中转',
        value: 1
    },
    {
        label: '直达',
        value: 2
    }
])
const isLoading = ref(true);
// 站点城市列表
const stationNameList = ref([]);
// 站点名称列表
const stationCityList = ref([]);
// 是否中转
const isTransfer = computed(() => {
     return dataForm.transferChoice==2;
})
/**
 * 表单提交
 */
const onSubmit = () => {
    // 校验
    dataFormRef.value.validate((valid) => {
        if (!valid) {
            proxy.Message.error("请检查输入信息是否正确");
        } else {
            proxy.Confirm({
                message: '确定提交？',
                okfun: async () => {
                    let params = {};
                    Object.assign(params, dataForm);
                    if (!params.startStationStartTime || params.startStationStartTime.length == 0) {
                        delete params.startStationStartTime;
                    }
                    if (!params.transferStationEndTime || params.transferStationEndTime.length == 0) {
                        delete params.transferStationEndTime;
                    }
                    if (!params.transferStationStartTime || params.transferStationStartTime.length == 0) {
                        delete params.transferStationStartTime;
                    }
                    if (!params.endStationEndTime || params.endStationEndTime.length == 0) {
                        delete params.endStationEndTime;
                    }
                    let result = await proxy.Request.request({
                        url: proxy.Api.addOrUpdateRoute,
                        params: params
                    });
                    if (!result) {
                        return;
                    }
                    proxy.Message.success("提交成功");
                    router.push({ name: 'route' });
                }
    })
        }
    })
}
/**
 * 获取站点城市列表
 */
const loadStationCityList = async()=>{
    let result = await proxy.Request.request({
        url: proxy.Api.loadStationCityList
    })
    if (!result) {
        return;
    }
    // 获取字符串并去掉首尾的方括号
    const dataString = result.data[0].slice(1, -1);

    // 使用逗号分割字符串，生成数组
    const dataArray = dataString.split(',').map(item => item.trim());

    // 追加到 stationNameList 中
    stationCityList.value.push(...dataArray);
}
/**
 * 加载数据
 */
 const loadData = async () => {
    isLoading.value = true; // 开启加载状态
    try {
        await Promise.all([loadStationCityList(), loadStationNameList()]);
    } catch (error) {
        console.error('加载站点数据出错:', error);
    } finally {
        isLoading.value = false; // 加载完成
    }
};
/**
 * 获取站点名称列表
 */
const loadStationNameList = async()=>{
    let result = await proxy.Request.request({
        url: proxy.Api.loadStationNameList
    })
    if (!result) {
        return;
    }
    // 获取字符串并去掉首尾的方括号
    const dataString = result.data[0].slice(1, -1);

    // 使用逗号分割字符串，生成数组
    const dataArray = dataString.split(',').map(item => item.trim());

    // 追加到 stationNameList 中
    stationNameList.value.push(...dataArray);
}
onMounted(async () => {
        await loadData();
        const row = route.query.row ? JSON.parse(route.query.row) : null;
        if (row) {
            dataForm.routeId = row.routeId;
            dataForm.trainNumber = row.trainNumber;
            dataForm.trainId = row.trainId;
            dataForm.startStationCity = row.startStationCity;
            dataForm.startStationName = row.startStationName;
            dataForm.transferStationCity = row.transferStationCity;
            dataForm.transferStationName = row.transferStationName;
            dataForm.endStationCity = row.endStationCity;
            dataForm.endStationName = row.endStationName;
            dataForm.startStationStartTime = row.startStationStartTime;
            dataForm.transferStationEndTime = row.transferStationEndTime;
            dataForm.transferStationStartTime = row.transferStationStartTime;
            dataForm.endStationEndTime = row.endStationEndTime;
            dataForm.businessRowStart = row.businessRowStart;
            dataForm.businessRowEnd = row.businessRowEnd;
            dataForm.commonRowStart = row.commonRowStart;
            dataForm.commonRowEnd = row.commonRowEnd;
            dataForm.businessPrice = row.businessPrice;
            dataForm.commonPrice = row.commonPrice;
            dataForm.status = row.status;
            if(row.transferStationName){
                dataForm.transferChoice = 1;
            }
        }
    })
</script>

<style scoped>
.el-form {
    .el-form-item {
        width: 400px;
    }
}
.loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
}
</style>